package threads;

import java.awt.EventQueue;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import main.GameDialog;
import main.GameFile;

public class FileSearcher extends Thread {

	private final GameDialog context;
	private final String dirname;
	private boolean isKilled;

	public FileSearcher(GameDialog context, String dirname) {
		this.context = context;
		this.dirname = dirname;
		isKilled = false;
	}

	@Override
	public void run() {
		ArrayList<GameFile> gamefiles = new ArrayList<GameFile>();
		long biggestTime = 0;
		
		//add files to filelist
		File startdir = new File(dirname);
		Stack<File> dirs = new Stack<File>();
		dirs.push(startdir);
		
		while(dirs.size()>0){
			File[] ff = dirs.pop().listFiles();
			if(ff!=null){
				for(File f : ff){
					if(f!=null){
						if(f.isDirectory()) dirs.push(f);
						else {
							String path = f.getAbsolutePath();
							path = path.substring(dirname.length(), path.length());
							long timestamp = f.lastModified();
							long size = f.length();
							if(timestamp>biggestTime) biggestTime = timestamp;
					
							gamefiles.add(new GameFile(path, timestamp, size));
					
							final String relPath = path;
							//kill
							if(isKilled) return;
							EventQueue.invokeLater(new Runnable(){
								@Override
								public void run() {
									context.reportFile(relPath);
								}
							});
						}
					}
				}
			}
		}
		
		final List<GameFile> list = gamefiles;
		final long big = biggestTime;
		//kill
		if(isKilled) return;
		EventQueue.invokeLater(new Runnable(){
			@Override
			public void run() {
				//add game to Tree
				context.reportDone(list, dirname, big);
			}
		});
	}
	
	public void kill(){
		isKilled = true;
	}

}
